package space.edge.d.demo.qrcode.codescanner.scanner;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import space.edge.d.demo.qrcode.common.Result;
import space.edge.d.demo.qrcode.R;
import space.edge.d.demo.qrcode.codescanner.camera.CameraManager;

/**
 * Created by gsl on 2017/10/27.
 * 预览handler
 */

public class PreviewHandler extends Handler {
    private final String TAG = PreviewHandler.class.getSimpleName();

    private final int STATE_SUCCESS = 0x00;
    private final int STATE_PREVIEW = 0x01;
    private final int STATE_DONE = 0x02;

    private DecodeThread decodeThread;
    private int state;
    private CameraManager cameraManager;

    private CameraPreview.ScannerCallback callback;

    int i = 0;

    PreviewHandler(CameraManager cm) {
        decodeThread = new DecodeThread(this);
        decodeThread.start();

        state = STATE_SUCCESS;
        cameraManager = cm;
        cameraManager.startPreview();
        restartPreviewAndDecode();
    }

    void setCallback(CameraPreview.ScannerCallback callback) {
        this.callback = callback;
    }

    CameraPreview.ScannerCallback getCallback() {
        return callback;
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case R.id.decode_succeeded:
                state = STATE_SUCCESS;
                Result result = (Result) msg.obj;
                Log.w(TAG, "解码成功");
                if (callback != null)
                    callback.onSuccess(result);
                break;
            case R.id.decode_failed:
                Log.w(TAG, "解码失败，进行第" + ++i + "次重试");
                state = STATE_PREVIEW;
                cameraManager.requestPreviewFrame(decodeThread.getHandler(), R.id.decode);
                if (callback != null)
                    callback.onFail();
                break;
        }
    }

    private void restartPreviewAndDecode() {
        if (state == STATE_SUCCESS) {
            state = STATE_PREVIEW;
            cameraManager.requestPreviewFrame(decodeThread.getHandler(), R.id.decode);
        }
    }

    public void quit() {
        state = STATE_DONE;
        cameraManager.stopPreview();
        Message quitMsg = Message.obtain(decodeThread.getHandler(), R.id.quit);
        quitMsg.sendToTarget();
        try {
            decodeThread.join(200L);
        } catch (InterruptedException e) {
            // do nothing
        }
        removeMessages(R.id.decode_succeeded);
        removeMessages(R.id.decode_failed);
    }

    CameraManager getCameraManager() {
        return cameraManager;
    }
}
